package com.liang.subject.domain.handler.subject;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.liang.subject.common.enums.SubjectInfoTypeEnum;
import com.liang.subject.domain.convert.JudgeSubjectConverter;
import com.liang.subject.domain.entity.SubjectAnswerBO;
import com.liang.subject.domain.entity.SubjectInfoBO;
import com.liang.subject.domain.entity.SubjectOptionBO;
import com.liang.subject.infra.basic.entity.SubjectJudge;
import com.liang.subject.infra.basic.service.SubjectJudgeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 判断题策略类
 */
@Component
@RequiredArgsConstructor
public class JudgeTypeHandler implements SubjectTypeHandler {

    private final SubjectJudgeService subjectJudgeService;

    @Override
    public SubjectInfoTypeEnum getSubjectType() {
        return SubjectInfoTypeEnum.JUDGE;
    }

    @Override
    public void save(SubjectInfoBO subjectInfoBO) {
        List<SubjectAnswerBO> optionList = subjectInfoBO.getOptionList();
        Preconditions.checkNotNull(optionList, "选项列表不能为空");
        List<SubjectJudge> judgeList = new ArrayList<>();
        optionList.forEach(option -> {
            SubjectJudge subjectJudge = new SubjectJudge();
            subjectJudge.setSubjectId(subjectInfoBO.getId());
            subjectJudge.setIsCorrect(option.getIsCorrect());
            judgeList.add(subjectJudge);
        });
        subjectJudgeService.saveBatch(judgeList);
    }

    @Override
    public SubjectOptionBO querySubjectInfo(Long subjectId) {
        SubjectJudge subjectJudge = subjectJudgeService.getBySubjectId(subjectId);
        List<SubjectAnswerBO> answerBOList = JudgeSubjectConverter.INSTANCE.convertPOToBOList(Collections.singletonList(subjectJudge));
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOptionList(answerBOList);
        return subjectOptionBO;
    }
}
